package pe.gob.foncodes.ssa.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.log4j.Logger;

public class Impresion {

    static final Logger log = Logger.getLogger(Impresion.class);

    public void imprimirListado(String nameReport, Collection coleccion)
            throws ClassNotFoundException, IOException, JRException {
        try {
            HashMap parameters = new HashMap();
            FacesContext context = FacesContext.getCurrentInstance();
            context.responseComplete();
            ServletContext scontext = (ServletContext) context.getExternalContext().getContext();
            String rutaReportes = scontext.getRealPath("\\reportes");
//            String rutaLogos = scontext.getRealPath("\\images");
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.addHeader("Content-disposition", "attachment; filename=" + nameReport + ".pdf");
            ServletOutputStream out = response.getOutputStream();
//            String rutaImagenlogo = rutaLogos + "\\" + nameLogoSucursal + ".png";
//            if (!"".equals(nameLogoCliente)) {
//                parameters.put("V_CRUTA", rutaImagenlogo);
//            }
//            parameters.put("V_ERUTA", rutaImagenlogo);
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(coleccion);
            File reporte = new File(rutaReportes + "\\" + nameReport + ".jasper");
            FileInputStream in = new FileInputStream(reporte);
            byte[] bytes = JasperRunManager.runReportToPdf(in, parameters, dataSource);
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex);
        } finally {
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
}
